
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Threading;
using System.Globalization;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ScrewTurn.Wiki {

	public partial class Language : BasePage {

		protected void Page_Load(object sender, EventArgs e) {
			Page.Title = "Language/Time Zone - " + Settings.WikiTitle;

			if(!Page.IsPostBack) {
				string[] c = Tools.AvailableCultures;
				lstLanguages.Items.Clear();
				//lstLanguages.Items.Add(new ListItem("English", "en-US"));
				for(int i = 0; i < c.Length; i++) {
					lstLanguages.Items.Add(new ListItem(c[i].Split('|')[1], c[i].Split('|')[0]));
				}

				HttpCookie cookie = Request.Cookies[Settings.CultureCookieName];
				string culture = "-";
				if(cookie != null) culture = cookie["C"];
				else culture = Settings.DefaultLanguage;
				SelectLanguage(culture);

				string timezone = "";
				if(cookie != null) timezone = cookie["T"];
				else timezone = Settings.DefaultTimezone;
				SelectTimeZone(timezone);

				if(!string.IsNullOrEmpty(Request["Language"])) {
					string lang = Request["Language"];

					SetPreferences(lang, lstTimezones.SelectedValue);
					SelectLanguage(lang);

					if(Request["Redirect"] != null) Response.Redirect(Request["Redirect"]);
					else if(Request.UrlReferrer != null && !string.IsNullOrEmpty(Request.UrlReferrer.ToString())) Response.Redirect(Request.UrlReferrer.ToString());
				}
			}

		}

		protected void btnSet_Click(object sender, EventArgs e) {
			string culture = lstLanguages.SelectedValue;
			string timezone = lstTimezones.SelectedValue;
			SetPreferences(culture, timezone);
		}

		private void SetPreferences(string culture, string timezone) {
			HttpCookie cookie = new HttpCookie(Settings.CultureCookieName);
			cookie.Expires = DateTime.Now.AddYears(10);
			cookie.Path = Settings.CookiePath;
			cookie.Values.Add("C", culture);
			cookie.Values.Add("T", timezone);
			Response.Cookies.Add(cookie);
			Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
			Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
		}

		private void SelectLanguage(string lang) {
			lstLanguages.SelectedIndex = -1;
			for(int i = 0; i < lstLanguages.Items.Count; i++) {
				if(lstLanguages.Items[i].Value.Equals(lang)) {
					lstLanguages.Items[i].Selected = true;
					break;
				}
			}
		}

		private void SelectTimeZone(string timezone) {
			lstTimezones.SelectedIndex = -1;
			for(int i = 0; i < lstTimezones.Items.Count; i++) {
				if(lstTimezones.Items[i].Value.Equals(timezone)) {
					lstTimezones.Items[i].Selected = true;
					break;
				}
			}
		}

	}

}
